package org.su.generalmvc.core;

import org.su.generalmvc.scheduler.SchedulerTask;
import org.su.generalmvc.scheduler.SecondSchedulerTask;
import org.su.scheduler.Scheduler;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;


/**
 * 管理所有控制器类的声明周期，集中处理他们的初始和结束方法
 * @author yangchuan
 * @version 1.0
 * @since 2012-03-06
 *
 */
public class LifeCycleManager {

		protected static final Log logger = LogFactory
				.getLog(LifeCycleManager.class);
		
		private static final LifeCycleManager instence = new LifeCycleManager();

		
		private List<LifeCycle> lifeCycles = new ArrayList<LifeCycle>();
		
		// 定时任务
		private Scheduler scheduler = new Scheduler();
	
		public static LifeCycleManager getInstence(){
			return instence;
		}
		
		public void add(LifeCycle lifeCycle) {
			lifeCycles.add(lifeCycle);
		}

		/**
		 * 初始化servlet 读取默认的 WEB-INF/application.xml 文件配置
		 * 调用publishAdapter初始化urlMapping
		 * 
		 * @throws javax.servlet.ServletException
		 *             if an error occurs
		 */
		public void init(IServiceContext serviceContext) throws ServiceException{
				logger.info("*** init begin ***");
				initCycle();
                try {
                    scheduler.start();
                }catch (Exception e){
                    logger.error(e);
                }
				logger.info("*** init end ***");
		}

		/**
		 * 结束清理生命周期控制器，停止定时任务
		 */
		public void destroy() {
			scheduler.stop();
			destroyCycle();
		}

		private void initCycle()  throws ServiceException{
			for (int i = 0; i < lifeCycles.size(); i++) {
				lifeCycles.get(i).init();
			}
		}

		private void destroyCycle() {
			for (int i = 0; i < lifeCycles.size(); i++) {
				lifeCycles.get(i).destroy();
			}
		}
		
		/**
		 * 添加定时任务
		 * @param crodTrigger
		 * @param controller
		 * @param method
		 */
		public void addTask(String crodTrigger, Object controller, Method method) {
			if (NumberUtils.isNumber(crodTrigger)) {
				// 秒任务
				this.scheduler.schedule("* * * * *", new SecondSchedulerTask(
						controller, method, Integer.parseInt(crodTrigger)));
			} else {
				// corn 任务
				this.scheduler.schedule(crodTrigger, new SchedulerTask(controller,
						method));
			}
		}
}
